<template>
  <view class="confirm-dialog-overlay" v-if="visible" @click="handleOverlayClick">
    <view class="confirm-dialog" @click.stop>
      <view class="dialog-header">
        <text class="dialog-title">订单确认</text>
      </view>
      
      <view class="dialog-content">
        <view class="info-row">
          <text class="info-label">产品</text>
          <text class="info-value">{{ orderInfo.materialType === 'GOLD' ? '黄金' : '白银' }}</text>
        </view>
        
        <view class="info-row">
          <text class="info-label">克重</text>
          <text class="info-value">{{ orderInfo.weight }}克</text>
        </view>
        
        <view class="info-row">
          <text class="info-label">单价</text>
          <text class="info-value price">{{ currentPrice || orderInfo.price }}元/克</text>
        </view>
        
        <view class="info-row">
          <text class="info-label">货款</text>
          <text class="info-value amount">{{ formatNumber(currentTotalAmount || orderInfo.totalAmount) }}元</text>
        </view>
        
        <view class="info-row">
          <text class="info-label">定金</text>
          <text class="info-value">{{ formatNumber(getDeposit()) }}元</text>
        </view>
        
        <view class="info-row">
          <text class="info-label">买/卖</text>
          <text class="info-value">{{ orderInfo.orderType === 'BUY' ? '买料' : '卖料' }}</text>
        </view>
      </view>
      
      <view class="dialog-buttons">
        <view class="btn btn-cancel" @click="handleCancel">
          <text class="btn-text">取消</text>
        </view>
        <view class="btn btn-confirm" @click="handleConfirm">
          <text class="btn-text">确认</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'OrderConfirmDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orderInfo: {
      type: Object,
      default: () => ({
        materialType: 'GOLD',
        weight: 0,
        price: 0,
        totalAmount: 0,
        deposit: 0,
        orderType: 'BUY'
      })
    }
  },
  data() {
    return {
      currentPrice: 0, // 当前实时价格
      currentTotalAmount: 0, // 当前实时货款总额
    }
  },
  watch: {
    // 监听订单信息变化
    'orderInfo.price': {
      handler(newVal) {
        this.currentPrice = newVal;
        this.updateTotalAmount();
      },
      immediate: true
    },
    // 监听visible变化，当对话框显示时重新获取最新价格
    visible: {
      handler(newVal) {
        if (newVal) {
          // 对话框显示时，立即获取最新价格
          this.getLatestPrice();
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 组件挂载时添加事件监听
    this.addPriceListener();
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    this.removePriceListener();
  },
  onUnload() {
    this.removePriceListener();
  },
  onLoad() {
    this.addPriceListener();
  },
  methods: {
    // 获取定金
    getDeposit() {
      // return Number(this.orderInfo.weight) * 20
	  let deposit = Number(this.orderInfo.weight) * 20;
	  if(uni.getStorageSync("appletConfig")){
	  	deposit =  Number(this.orderInfo.weight) * (Number(uni.getStorageSync("appletConfig").retainerStandard) /1000) ;
	  }
	  if(uni.getStorageSync("customerInfo")){
	  	if(uni.getStorageSync("customerInfo").retainerStandard){
	  		deposit =  Number(this.orderInfo.weight) * (Number(uni.getStorageSync("customerInfo").retainerStandard) / 1000) ;
	  	}
	  }
	  return deposit;
    },
    handleOverlayClick() {
      this.$emit('close')
    },
    handleCancel() {
      this.$emit('cancel')
    },
    handleConfirm() {
      this.$emit('confirm')
    },
    // 添加价格变化监听器
    addPriceListener() {
      uni.$on('priceMessagesChanged', (newMsg) => {
        // console.log('下单确认框价格变化：', newMsg.data.priceMap[this.orderInfo.materialType]);
        if(newMsg.data.priceMap[this.orderInfo.materialType]){
          if(this.orderInfo.orderType === 'BUY'){
            this.currentPrice = newMsg.data.priceMap[this.orderInfo.materialType].sellPrice;
            this.orderInfo.price = newMsg.data.priceMap[this.orderInfo.materialType].sellPrice;
          }else if(this.orderInfo.orderType === 'SELL'){
            this.currentPrice = newMsg.data.priceMap[this.orderInfo.materialType].price;
            this.orderInfo.price = newMsg.data.priceMap[this.orderInfo.materialType].price;
          }
          // 更新货款总额
          this.updateTotalAmount();
        }
      });
    },
    // 移除价格变化监听器
    removePriceListener() {
      uni.$off('priceMessagesChanged');
    },
    // 获取最新价格
    getLatestPrice() {
      // 从本地存储获取最新价格
      const materialType = this.orderInfo.materialType;
      let latestPrice = 0;
      
      if (materialType === 'GOLD') {
        const goldPrice = uni.getStorageSync('material_price_gold');
        if (goldPrice && goldPrice.priceData) {
          latestPrice = this.orderInfo.orderType === 'BUY' 
            ? goldPrice.priceData.price 
            : goldPrice.priceData.sellPrice;
        }
      } else if (materialType === 'SILVER') {
        const silverPrice = uni.getStorageSync('material_price_silver');
        if (silverPrice && silverPrice.priceData) {
          latestPrice = this.orderInfo.orderType === 'BUY' 
            ? silverPrice.priceData.price 
            : silverPrice.priceData.sellPrice;
        }
      }
      
      // 如果获取到最新价格，更新显示
      if (latestPrice > 0) {
        this.currentPrice = latestPrice;
        this.orderInfo.price = latestPrice;
        this.updateTotalAmount();
      }
    },
    // 更新货款总额
    updateTotalAmount() {
      this.currentTotalAmount = (Number(this.orderInfo.weight) * this.currentPrice).toFixed(2);
      this.orderInfo.totalAmount = this.currentTotalAmount;
    },
    // 格式化数字，添加千分符
    formatNumber(num) {
      if (num === null || num === undefined || num === '') {
        return '0.00';
      }
      // 将数字转换为字符串
      const numStr = num.toString();
      // 如果包含小数点，分别处理整数和小数部分
      if (numStr.includes('.')) {
        const parts = numStr.split('.');
        // 为整数部分添加千分符
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        return parts.join('.');
      } else {
        // 纯整数，添加千分符
        return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      }
    }
  }
}
</script>

<style scoped lang="scss">
.confirm-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.confirm-dialog {
  width: 90%;
  max-width: 600rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.dialog-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.dialog-content {
  margin-bottom: 40rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666666;
}

.info-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.info-value.price {
  color: #ff4757;
}

.info-value.amount {
  color: #2ed573;
}

.dialog-buttons {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  height: 80rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-cancel {
  background-color: #f5f5f5;
}

.btn-confirm {
  background-color: #333333;
}

.btn-text {
  font-size: 28rpx;
  font-weight: 500;
}

.btn-cancel .btn-text {
  color: #666666;
}

.btn-confirm .btn-text {
  color: #ffffff;
}
</style>
